<!--
 * @Description: 红包推广
 * @Author: liyujie
 * @Date: 2021/2/3
 * @Last Modified by: liyujie
 * @Last Modified time: 2021/2/3
-->
<template>
    <div
        class="couponExtension"
        v-if="dialogVisible && init"
    >
        <el-dialog
            title="红包推广"
            :visible.sync="dialogVisible"
            width="750px"
            :close-on-click-modal="false"
        >
            <p class="title">分享链接</p>
            <div class="url">
                <p class="link">
                    {{ host }}{{ share_url[TYPE] }}{{ formData.share_packet_no }}
                </p>
                <p
                    class="copy"
                    @click="copyUrl(host + share_url[TYPE] + formData.share_packet_no)"
                >
                    复制链接
                </p>
            </div>
            <div class="content">
                <p class="title">分享海报</p>
                <div
                    class="wrap"
                    id="canvasHtml"
                    ref="canvasHtml"
                >
                    <p class="wrap-title">掌上大学</p>
                    <p class="wrap-desc">送你一个红包</p>
                    <div class="side">

                        <div class="side-wrap">

                            <img
                                class="red-bg"
                                src="@/assets/image/red-packet-bg.png"
                            >
                            <img
                                class="red-bg-vague"
                                src="@/assets/image/red-packet-vague.png"
                            >
                            <div class="side-content">
                                <div class="content-left">
                                    <div
                                        class="side-num"
                                        v-if="formData.discount_num"
                                    >
                                        <span>￥</span>{{ Number(formData.discount_num).toFixed(2) }}
                                    </div>
                                    <div
                                        class="side-limit"
                                        v-if="formData.discount_limit_type === 1 || formData.discount_limit_type === 2"
                                    >
                                        满{{ formData.discount_limit }}{{ formData.discount_limit_type === 1 ? '元' : '件' }}可用
                                    </div>
                                    <div
                                        class="side-limit"
                                        v-if="formData.discount_limit_type === 0"
                                    >
                                        无门槛红包
                                    </div>
                                </div>
                                <div
                                    v-if="formData.title"
                                    class="content-right"
                                >
                                    {{ formData.title }}
                                </div>
                            </div>
                        </div>
                        <p class="side-date">
                            使用时间：{{ formData.get_start_time * 1000 | dateFormatter('yyyy/MM/dd') }}-{{ formData.get_end_time * 1000 | dateFormatter('yyyy/MM/dd') }}
                        </p>
                        <div class="qrcode-wrap">
                            <img
                                :src="code"
                                class="codeImg"
                                crossOrigin="anonymous"
                                ref="codeImg"
                            >
                        </div>
                        <p class="code-desc">
                            长按识别二维码
                        </p>
                    </div>
                </div>
                <div class="button">
                    <p
                        class="button-wrap"
                        @click="downHb()"
                    >
                        下载海报
                    </p>
                    <p
                        class="button-wrap"
                        @click="downLoadCode(code, formData.title)"
                    >
                        下载二维码
                    </p>
                    <div class="count-view">
                        <div>红包总量：{{ formData.total_num_max }} 个</div>
                        <div style="margin-top: 20px">红包已发放量：<span class="num-view">{{ formData.get_count }} 个</span></div>
                        <div style="margin-top: 20px">
                            红包当前推广数量：
                            <span v-show="!isEdit"><span class="num-view">{{ total_num }}</span></span>
                            <el-input-number
                                v-model="total_num"
                                size="mini"
                                :step="1"
                                :min="formData.get_count"
                                :max="formData.total_num_max"
                                step-strictly
                                style="width: 100px"
                                v-show="isEdit"
                            />
                            <span class="num-view">个</span>
                            <el-button
                                type="text"
                                v-show="!isEdit"
                                @click="setEditable(true)"
                            >
                                修改数量
                            </el-button>
                            <el-button
                                type="text"
                                v-show="isEdit"
                                @click="setEditable(false)"
                            >
                                取消
                            </el-button>
                            <el-button
                                type="text"
                                v-show="isEdit"
                                @click="setCount"
                            >
                                确认
                            </el-button>
                        </div>
                        <div style="margin-top: 20px">红包剩余推广数量：<span class="num-view">{{ formData.total_num - formData.get_count }} 个</span></div>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import html2canvas from 'html2canvas';

export default {
    data () {
        return {
            dialogVisible: false,
            formData: {},
            share_url: {
                single: '/pages/mall/coupon/coupon-detail-single?packet_no=',
                multi: '/pages/mall/coupon/coupon-detail-multi?packet_no='
            },//分享链接
            TYPE: '',//单:single multi:双
            init: false,
            code: '',//二维码图片地址
            host: '',
            // 推广数量
            total_num: 1,
            // 红包编号
            packet_no: '',
            // 编辑数量开关
            isEdit: false
        };
    },
    mounted () {
        this.host = this.$studentBaseUrl;
    },
    methods: {
        /**
         * @description 初始化弹窗
         */
        show (packet_no) {
            this.dialogVisible = true;

            if(!packet_no) {
                this.$notify({
                    title: '提示',
                    message: '红包编号为空',
                    type: 'warning',
                    duration: 2000
                });
                return false;
            }

            this.packet_no = packet_no;
            this.getPromote(packet_no);
        },

        /**
         * @description 关闭弹窗
         */
        close () {
            this.dialogVisible = false;
        },

        /**
         * @description 获取推广信息
         * @param packet_no - 红包编号
         */
        getPromote (packet_no) {
            this.$post('/student/shop_goods_red_packet%5Cget_promote',{
                packet_no: packet_no
            },resp=>{
                if (resp.code == 1) {
                    this.formData = {
                        ...resp.data
                    };
                    this.total_num = resp.data.total_num;
                    this.TYPE = this.formData.is_single_goods === 1 ? 'single' : 'multi';
                    this.getCode(this.formData.share_packet_no);
                    this.init = true;
                } else if (resp.code == 0) {
                    this.$notify({
                        title: '提示',
                        message: resp.msg,
                        type: 'warning',
                        duration: 2000
                    });
                }
            });
        },

        /**
         * @description 获取二维码
         * @param share_packet_no
         */
        getCode (share_packet_no) {
            let base = this.$baseUrl;
            let ticket = localStorage.getItem('sessionTicket');
            let url = this.$studentBaseUrl + `${this.share_url[this.TYPE]}` + share_packet_no;

            this.code = `${base}/__local/common%5Cqrcode?content=${url}&__ticket=${ticket}`;
        },

        /**
         * @description 下载二维码
         */
        downLoadCode (src,imgName) {
            let canvas = document.createElement('canvas');
            let img = document.createElement('img');

            img.onload = function(e) {
                canvas.width = img.width;
                canvas.height = img.height;
                let context = canvas.getContext('2d');

                context.drawImage(img, 0, 0, img.width, img.height);
                canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
                canvas.toBlob((blob) => {
                    let link = document.createElement('a');

                    link.href = window.URL.createObjectURL(blob);
                    link.download = imgName.split('.')[0];
                    link.click();
                },
                "image/png");
            };
            img.crossOrigin = "Anonymous";
            img.src = src;
        },

        /**
         * @description 下载海报
         */
        downHb () {
            html2canvas(this.$refs.canvasHtml,{
                backgroundColor: null,
                allowTaint: false,
                taintTest: true,
                useCORS:true,
                scale: 3,
                dpi: 300
            }).then((canvas) => {
                document.body.appendChild(canvas);
                let dataURL = canvas.toDataURL("image/png");

                this.fnDownLoadFile(this.formData.title + '.png', dataURL);
            });
        },

        /**
         * @description 下载base64图片
         * @param   {String}    fileName        //图片名称
         * @param   {String}    content         //base64
         */
        fnDownLoadFile (fileName, content) {
            let aLink = document.createElement('a');
            let blob = this.base64ToBlob(content);
            let evt = document.createEvent("HTMLEvents");

            //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
            evt.initEvent("click", true, true);
            aLink.download = fileName;
            aLink.href = URL.createObjectURL(blob);
            //兼容火狐
            aLink.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));
        },

        /**
         * @description base64转换blob
         */
        base64ToBlob(code) {
            let parts = code.split(';base64,');
            let contentType = parts[0].split(':')[1];
            let raw = window.atob(parts[1]);
            let rawLength = raw.length;
            let uInt8Array = new Uint8Array(rawLength);

            for (let i = 0; i < rawLength; ++i) {
                uInt8Array[i] = raw.charCodeAt(i);
            }
            return new Blob([uInt8Array], {type: contentType});
        },

        /**
         * @description 复制链接
         */
        copyUrl (url) {
            let str = url;
            let oInput = document.createElement("input");

            oInput.value = str;
            document.body.appendChild(oInput);
            oInput.select();
            document.execCommand("Copy");
            oInput.style.display = "none";
            this.$notify({
                title: '提示',
                message: '复制成功',
                type: 'success',
                duration: 2000
            });
        },

        /**
         * 修改数量
         */
        setEditable(flag) {

            this.isEdit = flag;
            if (flag) this.tempCount = this.total_num;
            if (!flag) {
                this.total_num = this.tempCount;
            }
        },

        /**
         * 确认设置数量
         */
        setCount() {

            this.$post('/student/shop_goods_red_packet%5Cset_promote_num',{
                packet_no: this.packet_no,
                total_num: this.total_num
            },resp=>{
                if (resp.code === 1) {
                    this.isEdit = false;
                    this.getPromote(this.packet_no);
                    this.$emit('update');
                } else {
                    this.$notify({
                        title: '提示',
                        message: resp.msg,
                        type: 'warning',
                        duration: 2000
                    });
                }
            });
        }
    }
};
</script>

<style lang="less" scoped>
.couponExtension {
    .title {
        color: rgba(51, 51, 51, 1);
        height: 20px;
        line-height: 20px;
        font-weight: 500;
        font-size: 14px;
        margin-bottom: 12px;
    }
    .url {
        width: 100%;
        height: 20px;
        display: flex;
        align-items: center;
        margin-bottom: 24px;
        .link {
            color: rgba(51, 51, 51, 1);
            font-size: 12px;
            margin-right: 10px;
            line-height: 22px;
        }
        .copy {
            color: rgba(24, 144, 255, 1);
            font-size: 12px;
            text-decoration: underline;
            cursor: pointer;
            white-space: nowrap;
        }
    }
    .content {
        width: 100%;
        height: 356px;
        display: flex;
        align-items: flex-start;
        .title {
            color: rgba(51, 51, 51, 1);
            height: 20px;
            line-height: 20px;
            font-size: 14px;
            font-weight: 500;
            margin-right: 24px;
        }
        .wrap {
            width: 240px;
            height: 356px;
            background: linear-gradient(315deg, #FF0844 0%, #FF8864 100%);
            display: flex;
            flex-direction: column;
            box-sizing: border-box;
            padding: 10px;
            border-radius: 8px;
            position: relative;

            .wrap-title {
                height: 20px;
                margin-bottom: 6px;
                line-height: 20px;
                color: #ffffff;
                font-size: 14px;
                font-family: PingFangSC-Medium, PingFang SC;
                font-weight: 500;
            }

            .wrap-desc {
                height: 17px;
                line-height: 17px;
                margin-bottom: 12px;
                color: #ffffff;
                font-size: 12px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
            }

            .logo {
                position: absolute;
                top: 10px;
                right: 10px;
                width: 24px;
                height: 24px;
            }

            .side {
                width: 220px;
                height: 281px;
                background-color: #ffffff;
                border-radius: 8px;
                display: flex;
                flex-direction: column;
                align-items: center;
                box-sizing: border-box;
                position: relative;

                .side-bg {
                    width: 210px;
                    height: 144px;
                    position: absolute;
                    left: 0;
                    top: 9px;
                    z-index: 0;
                }

                .side-wrap {
                    width: 200px;
                    height: 105px;
                    border: 6px solid #FF8162;
                    background: #fff;
                    border-radius: 8px;
                    margin-top: 10px;
                    position: relative;
                    .red-bg {
                        position: absolute;
                        right: -6px;
                        top: -6px;
                    }
                    .red-bg-vague {
                        position: absolute;
                        right: 22px;
                        top: 0;
                    }

                    .side-content {
                        width: 100%;
                        height: 100%;
                        display: flex;
                        position: absolute;
                        .content-left {
                            flex: 1;
                            display: flex;
                            flex-direction: column;
                            justify-content: center;
                            align-items: center;
                            .side-num {
                                font-size: 20px;
                                font-family: Avenir-Black, Avenir;
                                font-weight: 900;
                                color: #FF364F;
                                margin-left: -10px;
                                span {
                                    font-size: 12px;
                                }
                            }
                            .side-limit {
                                font-size: 10px;
                                font-family: PingFangSC-Regular, PingFang SC;
                                font-weight: 400;
                                color: #A4878A;
                                margin-top: 10px;
                                margin-left: -8px;
                            }
                        }
                        .content-right {
                            flex: 1;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            font-family: PingFangSC-Medium, PingFang SC;
                            font-weight: 500;
                            color: #FFFFFF;
                            text-align: center;
                            line-height: 22px;
                        }
                    }
                }
                .side-date {
                    margin-top: 9px;
                    letter-spacing: 0;
                    font-size: 10px;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #999999;
                }
                .qrcode-wrap {
                    width: 94px;
                    height: 94px;
                    margin-top: 18px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    border: 1px solid #F0F2F5;
                }
                .codeImg {
                    width: 82px;
                    height: 82px;
                }
                .code-desc {
                    margin-top: 4px;
                    font-size: 10px;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #333333;
                }
            }
        }
        .button {
            display: flex;
            flex-direction: column;
            margin-left: 24px;
            .button-wrap {
                width: 96px;
                height: 36px;
                border-radius: 4px;
                background-color: rgba(24, 144, 255, 1);
                text-align: center;
                line-height: 36px;
                color: #ffffff;
                font-size: 14px;
                font-weight: 500;
                cursor: pointer;
                margin-bottom: 32px;
            }
        }
    }

    .count-view {
        color: #666;
        .num-view {
            color: #333;
        }
    }
}
</style>
<style lang="less">
.couponExtension {
    .el-dialog {
        margin-top: 15vh !important;
    }
    .el-dialog__body {
        padding: 24px 32px;
    }
}
</style>
